import IndexModel from "../../models/IndexModel";
const indexModel = new IndexModel();
const app = getApp();
// pages/company/company.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    companyDetail: {},
    titleArr: [],
    isFavor: false,
    type: '1', // type - 1 website 2 zixun 3 jinnang
    id: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // console.log('company->', options, this.data.type);
    wx.showLoading({
      title: '加载中',
    })
    Promise.all([
      indexModel.getClassifyCompanyList(options.id),
      indexModel.getTitleDesc(app.globalData.userId),
      indexModel.judgeFavor(options.id, this.data.type, app.globalData.userId),
    ])
    .then(res => {
      let companyDetail = res[0].ListJson[0];
      // console.log('company->', companyDetail);
      if(companyDetail.fenleibiaoqian) {
        companyDetail.label = companyDetail.fenleibiaoqian.split(',');
      }
      let titleArr = this.handleTitleDesc(res[1].JSONdata, companyDetail);
      // console.log('titleArr->', titleArr);
      let isFavor = res[2] && res[2].IsMark === '1';
      this.setData({
        companyDetail,
        titleArr,
        id: options.id,
        isFavor,
      })
      wx.hideLoading();
    }).catch(e => {
      console.error(e)
      wx.hideLoading();
    })
  },

  handleTitleDesc(titleArr, detail) {
    titleArr.forEach(item => {
      let key = item.jyCompanyziduan;
      if (detail[key]) {
        let _match = detail[key].match(/(\<image\>)(.*)(\<\/image\>)/);
        if (_match) {
          item.value = detail[key].split(_match[0]).join('');
          item.url = _match[2];
        } else {
          item.value = detail[key];
        }
        // let _c = detail[key].split('\n');
        // console.log('company-66-->', _c);
        // let value = detail[key].split('\n').join('\n');
        // value = value.split('\t').join('\t');
        // console.log('company-68-->', value);
        // item.value = value;
      }
    });
    // console.log('titleArr->', titleArr);
    
    return titleArr;
  },

  clickFavor(e) {
    let sel = e.detail.sel;
    let {
      id,
      type
    } = this.data;
    indexModel.favor('1', type, id, sel, app.globalData.userId).then(res => {
      // console.log('favor22222->', res);
      wx.showToast({
        title: '成功',
        icon: 'success',
        duration: 2000,
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})